package org.jeecg.modules.yw.controller;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.ibatis.annotations.Param;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.system.api.ISysBaseAPI;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.yw.entity.WorkerCompanyRelation;
import org.jeecg.modules.yw.service.EnterPriseService;
import org.jeecg.modules.yw.service.IWorkerCompanyRelationService;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import lombok.extern.slf4j.Slf4j;

import org.jeecg.modules.yw.utils.CommonUtils;
import org.jeecgframework.poi.excel.ExcelImportUtil;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.ImportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.jeecg.common.system.base.controller.JeecgController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.servlet.ModelAndView;
import com.alibaba.fastjson.JSON;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.jeecg.common.aspect.annotation.AutoLog;

/**
 * @Description: 内勤工人表
 * @Author: jeecg-boot
 * @Date: 2025-04-22
 * @Version: V1.0
 */
@Api(tags = "内勤工人表")
@RestController
@RequestMapping("/yw/workerCompanyRelation")
@Slf4j
public class WorkerCompanyRelationController extends JeecgController<WorkerCompanyRelation, IWorkerCompanyRelationService> {
    @Autowired
    private IWorkerCompanyRelationService workerCompanyRelationService;
    @Autowired
    private EnterPriseService enterPriseService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;

    /**
     * 分页列表查询
     *
     * @param name
     * @param pageNo
     * @param pageSize
     * @return
     */
    //@AutoLog(value = "内勤工人表-分页列表查询")
    @ApiOperation(value = "内勤工人表-分页列表查询", notes = "内勤工人表-分页列表查询")
    @GetMapping(value = "/list")
    public Result<IPage<WorkerCompanyRelation>> queryPageList(@RequestParam(name = "name", required = false) String name,
                                                              @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                                              @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize) {
        Page<WorkerCompanyRelation> page = new Page<>(pageNo, pageSize);
        IPage<WorkerCompanyRelation> pageList = workerCompanyRelationService.pageInfo(page, name);
        List<WorkerCompanyRelation> pageListRecords = pageList.getRecords();
        if (pageListRecords != null && pageListRecords.size() > 0) {
            for (int i = 0; i < pageListRecords.size(); i++) {
                WorkerCompanyRelation workerCompanyRelation = pageListRecords.get(i);
                setModel(workerCompanyRelation);
            }
        }
        return Result.OK(pageList);
    }

    @AutoLog(value = "内勤工人表-列表查询")
    @GetMapping(value = "/listWorker")
    public Result nqlist(@Param("ids") String ids) {
        List<String> roleidstr = Arrays.asList(ids.split(","));
        return Result.OK(workerCompanyRelationService.nqlist(roleidstr));
    }

    private void setModel(WorkerCompanyRelation workerCompanyRelation) {
        String companyId = workerCompanyRelation.getCompanyId();
        if (StringUtils.isNotBlank(companyId)) {
            List<String> companyIdList = new ArrayList();
            StringBuffer sb = new StringBuffer();
            String[] companyIds = companyId.split(",");
            for (int j = 0; j < companyIds.length; j++) {
                String company = companyIds[j];
                String nameS = enterPriseService.getById(company).getName();
                sb.append(nameS).append(",");
                companyIdList.add(company);
            }
            workerCompanyRelation.setCompanyNames(sb.toString().substring(0, sb.toString().length() - 1));
            workerCompanyRelation.setCompanyIdList(companyIdList);
        }
        String workerId = workerCompanyRelation.getWorkerId();
        if (StringUtils.isNotBlank(workerId)) {
            LoginUser user= sysBaseAPI.getUserById(workerId);
            workerCompanyRelation.setWorkerName(user.getRealname());
        }
    }

    /**
     * 添加
     *
     * @param workerCompanyRelation
     * @return
     */
    @AutoLog(value = "内勤工人表-添加")
    @ApiOperation(value = "内勤工人表-添加", notes = "内勤工人表-添加")
    //@RequiresPermissions("org.jeecg.modules:worker_company_relation:add")
    @PostMapping(value = "/add")
    public Result<String> add(@RequestBody WorkerCompanyRelation workerCompanyRelation) {
        if (workerCompanyRelationService.getOne(new QueryWrapper<WorkerCompanyRelation>()
                .eq("workerId", workerCompanyRelation.getWorkerId())) != null) {
            return Result.error("该用户已存在");
        }
        String companyId = workerCompanyRelation.getCompanyId();
        if (StringUtils.isNotBlank(companyId) && companyId.indexOf("[") >= 0) {
            setInfo(workerCompanyRelation, companyId);
            return Result.OK("添加成功！");
        } else {
            return Result.error("请选择企业");
        }
    }

    private void setInfo(WorkerCompanyRelation workerCompanyRelation, String companyId) {
        companyId = companyId.substring(1, companyId.length() - 2).replaceAll("\"", "");
        String[] companyIdList = companyId.split(",");
        for (int i = 0; i < companyIdList.length; i++) {
            WorkerCompanyRelation relation = new WorkerCompanyRelation();
            relation.setId(CommonUtils.getID());
            relation.setCompanyId(companyIdList[i]);
            relation.setWorkerId(workerCompanyRelation.getWorkerId());
            workerCompanyRelationService.save(relation);
        }
    }

    /**
     * 编辑
     *
     * @param workerCompanyRelation
     * @return
     */
    @AutoLog(value = "内勤工人表-编辑")
    @ApiOperation(value = "内勤工人表-编辑", notes = "内勤工人表-编辑")
    //@RequiresPermissions("org.jeecg.modules:worker_company_relation:edit")
    @RequestMapping(value = "/edit", method = {RequestMethod.PUT, RequestMethod.POST})
    public Result<String> edit(@RequestBody WorkerCompanyRelation workerCompanyRelation) {
        workerCompanyRelationService.remove(new QueryWrapper<WorkerCompanyRelation>()
                .eq("worker_id", workerCompanyRelation.getWorkerId()));
        String companyId = workerCompanyRelation.getCompanyId();
        if (StringUtils.isNotBlank(companyId) && companyId.indexOf("[") >= 0) {
            setInfo(workerCompanyRelation, companyId);
            return Result.OK("修改成功！");
        } else {
            return Result.error("请选择企业");
        }
    }

    /**
     * 通过id删除
     *
     * @param id
     * @return
     */
    @AutoLog(value = "内勤工人表-通过id删除")
    @ApiOperation(value = "内勤工人表-通过id删除", notes = "内勤工人表-通过id删除")
    //@RequiresPermissions("org.jeecg.modules:worker_company_relation:delete")
    @DeleteMapping(value = "/delete")
    public Result<String> delete(@RequestParam(name = "id", required = true) String id) {
        workerCompanyRelationService.remove(new QueryWrapper<WorkerCompanyRelation>()
                .eq("worker_id", id));
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     *
     * @param ids
     * @return
     */
    @AutoLog(value = "内勤工人表-批量删除")
    @ApiOperation(value = "内勤工人表-批量删除", notes = "内勤工人表-批量删除")
    //@RequiresPermissions("org.jeecg.modules:worker_company_relation:deleteBatch")
    @DeleteMapping(value = "/deleteBatch")
    public Result<String> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        workerCompanyRelationService.remove(new QueryWrapper<WorkerCompanyRelation>()
                .eq("worker_id", ids.split(",")));
        return Result.OK("批量删除成功!");
    }

    /**
     * 通过id查询
     *
     * @param id
     * @return
     */
    //@AutoLog(value = "内勤工人表-通过id查询")
    @ApiOperation(value = "内勤工人表-通过id查询", notes = "内勤工人表-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<WorkerCompanyRelation> queryById(@RequestParam(name = "id", required = true) String id) {
        WorkerCompanyRelation workerCompanyRelation = workerCompanyRelationService.getById(id);
        setModel(workerCompanyRelation);
        if (workerCompanyRelation == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(workerCompanyRelation);
    }

    /**
     * 导出excel
     *
     * @param request
     * @param workerCompanyRelation
     */
    //@RequiresPermissions("org.jeecg.modules:worker_company_relation:exportXls")
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, WorkerCompanyRelation workerCompanyRelation) {
        return super.exportXls(request, workerCompanyRelation, WorkerCompanyRelation.class, "内勤工人表");
    }

    /**
     * 通过excel导入数据
     *
     * @param request
     * @param response
     * @return
     */
    //@RequiresPermissions("worker_company_relation:importExcel")
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, WorkerCompanyRelation.class);
    }

}
